package Reaction::InterfaceModel::Action;

use Reaction::Meta::InterfaceModel::Action::Class;
use Moose::Meta::Attribute;
use aliased 'Reaction::Meta::InterfaceModel::Action::ParameterAttribute';

use metaclass 'Reaction::Meta::InterfaceModel::Action::Class';
use Reaction::Class;

class Action which {

  has target_model => (is => 'ro', required => 1,
                         metaclass => 'Moose::Meta::Attribute');
  
  has ctx => (isa => 'Catalyst', is => 'ro', required => 1,
                metaclass => 'Moose::Meta::Attribute');
  
  implements parameter_attributes => as {
    my ($self) = @_;
    return grep { $_->isa(ParameterAttribute) }
             $self->meta->compute_all_applicable_attributes;
  };
  
  implements parameter_hashref => as {
    my ($self) = @_;
    my %params;
    foreach my $attr ($self->parameter_attributes) {
      my $reader = $attr->reader;
      my $predicate = $attr->predicate;
      next if defined($predicate) && !$self->$predicate;
      $params{$attr->name} = $self->$reader;
    }
    return \%params;
  };
  
  implements can_apply => as {
    my ($self) = @_;
    foreach my $attr ($self->parameter_attributes) {
      my $predicate = $attr->predicate;
      if ($attr->is_required) {
        return 0 unless $self->$predicate;
      }
      if ($attr->has_valid_values) {
        unless ($predicate && !($self->$predicate)) { 
          my $reader = $attr->reader;
          return 0 unless $attr->check_valid_value($self, $self->$reader);
        }
      }
    }
    return 1;
  };
  
  implements error_for => as {
    my ($self, $attr) = @_;
    confess "No attribute passed to error_for" unless defined($attr);
    unless (ref($attr)) {
      my $meta = $self->meta->find_attribute_by_name($attr);
      confess "Can't find attribute ${attr} on $self" unless $meta;
      $attr = $meta;
    }
    return $self->error_for_attribute($attr);
  };
  
  implements error_for_attribute => as {
    my ($self, $attr) = @_;
    if ($attr->is_required) {
      my $predicate = $attr->predicate;
      unless ($self->$predicate) {
        return $attr->name." is required";
      }
    }
    if ($attr->has_valid_values) {
      my $reader = $attr->reader;
      unless ($attr->check_valid_value($self, $self->$reader)) {
        return "Not a valid value for ".$attr->name;
      }
    }
    return; # ok  
  };
  
  sub sync_all { }

};

1;
